package com.wwwc.index.web.servlet;

import java.io.*;
import java.awt.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletRequestWrapper;
import java.net.*;

import javax.ejb.*;
import javax.naming.*;
import java.rmi.*;
import javax.rmi.*;

import com.wwwc.util.web.*;
import com.wwwc.index.web.ejb.database.*;

public class ContentDisplayServlet extends HttpServlet {
    private EJBDatabaseQuery ejbdb;
 
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    {
	doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
    {
	try{
	    response.setContentType("text/html");
	    PrintWriter out      = response.getWriter();
	    HttpSession session  = request.getSession(true);

	    String call_path     = request.getContextPath()+request.getServletPath();
	    String user_ip       = request.getRemoteAddr();
	    String mid           = (String)request.getAttribute("mid");
	    String action        = request.getParameter("aid");

	    if(mid == null) {
		System.out.println("ContentDisplayServlet:Error:101");
		return;
	    }

	    String pid =  request.getParameter("pid");
	    if(pid == null || !MyStringCheck.isNumber(pid)) {
		pid = "1";
	    }

	    String table_name    = request.getParameter("table_name");
	    String sub_dir       = request.getParameter("sub_dir");
	    String max_rows      = request.getParameter("max_rows");

	    if(table_name == null || sub_dir == null || max_rows == null) {
		System.out.println("ContentDisplayServlet:Error:102");
		return;
	    }

	    String user_name    = null;
	    int user_age        = 0;
	    int user_level      = 0;
	    String user_fname   = null;
	    String user_since   = null;
	    String user_edu     = null;
	    String user_zip     = null;
	    String user_sex     = null;
	    String screen_w     = null;
	    String screen_h     = null;

	    Hashtable user_info = (Hashtable)session.getAttribute("user_info");
	    if(user_info == null) {
		System.out.println("ContentDisplayServlet:Error:104");
		return;
	    }

	    user_name   = (String)user_info.get("user_name");
	    user_age    = Integer.parseInt((String)user_info.get("user_age"));
	    user_level  = Integer.parseInt((String)user_info.get("user_level"));
	    user_fname  = (String)user_info.get("user_fname");
	    user_since  = (String)user_info.get("user_since");
	    user_edu    = (String)user_info.get("user_edu");
	    user_zip    = (String)user_info.get("user_zip");
	    user_sex    = (String)user_info.get("user_sex");
	    screen_w    = (String)user_info.get("screen_w");
	    screen_h    = (String)user_info.get("screen_h");

	    if(screen_w == null || screen_h == null) {
		screen_w = "1280";
		screen_h = "1024";
	    }

	    int sw = Integer.parseInt(screen_w);
	    int sh = Integer.parseInt(screen_h);

	    //////////////////////////////////////////////////////////////////////////////
	    // access control
	    //////////////////////////////////////////////////////////////////////////////

	    Hashtable achs = (Hashtable)request.getAttribute("achs");
	    if(achs == null) {
		return;
	    }

	    int read_level     = Integer.parseInt((String)achs.get("read_level"));
	    int read_age       = Integer.parseInt((String)achs.get("read_age"));
	    int post_level     = Integer.parseInt((String)achs.get("post_level"));
	    int post_age       = Integer.parseInt((String)achs.get("post_age"));

	    boolean manager  = (Boolean.valueOf((String)achs.get("show_manager"))).booleanValue();
	    boolean admin    = (Boolean.valueOf((String)achs.get("show_admin"))).booleanValue();

	    out.println((new ServletBean()).getSubdirInfo(request));

	    ContentDisplayBean cbean = new ContentDisplayBean();

	    //===========================================================================
	    // preview (0) listContent
	    //===========================================================================

	    if(action == null || action.equals("0")) {
		out.println(cbean.getPageCounter(request, call_path, mid, sub_dir, table_name, max_rows, pid, admin));
		if(post_level <= user_level) {
		    out.println(cbean.getAddAndSearchBar(call_path, mid, "2", "0-1", admin, manager));
		}
		out.println(cbean.listContent(request, call_path, mid, "0", table_name, sub_dir, max_rows, pid, admin, manager, "1"));
		return;
	    }

	    /////////////////////////////////////////////////////////////////////////////
	    // preview (0) search list 
	    /////////////////////////////////////////////////////////////////////////////

	    if(action != null && action.equals("0-1")) {
		String search = request.getParameter("sq");
		String field[]={"FIELD5","FIELD11"};
		StringBuffer sbf = cbean.listSearchResults(call_path, mid, search, table_name, pid, max_rows, field, "1");
		out.println(sbf);
	    }

	    //====================================================================
	    // detail review [1-*]
	    //====================================================================
	    
	    if(action != null && action.equals("1")) {
		String f1  = request.getParameter("f1");
		if(f1==null || f1.length()==0) {
		    return;
		}

		StringBuffer sbf = cbean.addNewPost(request, call_path, mid, "2", user_name, user_level, manager, 
						    admin, read_level, read_age);

		out.println(cbean.displayDetail(request, call_path, mid, table_name, f1, pid, manager,admin, user_name, sbf));
	    }	

	    //===================================================================
	    // Add  (new and reply) [2-*]
	    //===================================================================
	    
	    if(action != null && action.equals("2")) {	       
		StringBuffer error = cbean.addNewPost(request, call_path, mid, action, user_name, user_level,
						      manager, admin, read_level, read_age);
		if(error == null) {
		    try {
			RequestDispatcher rd = request.getRequestDispatcher(request.getServletPath()+"?mid="+mid+"&aid=0&pid="+pid); 
			rd.forward(request,response);
		    }
		    catch (Exception e) {
			System.out.println("ContentDisplayServlet:Error:2:"+e);
		    }
		} 
		else {
		    out.println(error);
		}		    
	    }	
	    

	    if (ejbdb == null) {
		ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	    }

	    String query = null;

	    //===================================================================
	    // Manager (Edit, Remove) [3-*]
	    //===================================================================

	    if(action != null && action.equals("3-1")) {
		//StringBuffer sbf = new StringBuffer();
		String f1 = request.getParameter("f1");
		out.println(cbean.singlePageEditForm(call_path, mid, table_name, f1, "3-2", pid));
	    }

	    // save edit

	    if(action != null && action.equals("3-2")) {
		if(cbean.saveUpdate(request)) {
		    try{
			RequestDispatcher rd = request.getRequestDispatcher(request.getServletPath()+"?mid="+mid+"&aid=0&pid="+pid); 
			rd.forward(request,response);
		    }
		    catch (Exception e) {
			out.println("Update Error.");
		    }
		}
		else {
		    System.out.println("ContentDisplayServlet:Error:3-2");
		}
	    }

	    // remove 3-3
	    if(action != null && action.equals("3-3")) {
		String f1 = request.getParameter("f1");
		query = "UPDATE "+table_name+" SET FIELD17='-1' WHERE FIELD1="+f1+";";
		ejbdb.update(query);
		try {
		    RequestDispatcher rd = request.getRequestDispatcher(request.getServletPath()+"?mid="+mid+"&aid=0&pid="+pid); 
		    rd.forward(request,response);
		}
		catch (Exception e) {
		    System.out.println("ContentDisplayServlet:Error:3-3:"+e);
		}
	    }

	    ////////////////////////////////////////////////////////////////////////////
	    // admin (4) [delete]
	    ////////////////////////////////////////////////////////////////////////////

	    if(action != null && action.equals("4")) {
		String f1 = request.getParameter("f1");
		query = "DELETE FROM "+table_name+" WHERE FIELD1="+f1+";";
		ejbdb.delete(query);
		try {
		    RequestDispatcher rd = request.getRequestDispatcher(request.getServletPath()+"?mid="+mid+"&aid=0&pid="+pid); 
		    rd.forward(request,response);
		}
		catch (Exception e) {
		    System.out.println("ContentDisplayServlet:Error:4:"+e);
		}
	    }

	    /*
	    
	    ////////////////////////////////////////////////////////////////////////////
	    // manager or admin single page edit
	    ////////////////////////////////////////////////////////////////////////////

	    if(action.equals("2-0")) { //single page manager or admin edit
		if(user_name == null || !(ServletBean.isManager(request, user_name, ";") ||
					 user_level>90 && user_ip.startsWith(local_ips))) {
		    return;
		}
		
		StringBuffer sbf3 = new StringBuffer();
		f1 = request.getParameter("f1");

		sbf3 = ((new ContentDisplayBean()).singlePageEditForm(f1, table_name, pid, sid, "2-1"));
		out.println(MyHtml.forumDisplay(sid, ad_left, sbf3, ad_right));
		return;
	    }

	    ///////////////////////////////////////////////////////////////////
	    // save single page update
	    ///////////////////////////////////////////////////////////////////

	    if(action.equals("2-1")) {
		ContentDisplayBean cbean = new ContentDisplayBean();
		if(cbean.saveUpdate(request)) {
		    RequestDispatcher rd = request.getRequestDispatcher("MainBarServlet?sid="+sid+"&aid=1-0&pid="+pid); 
		    rd.forward(request,response);
		}
		else {
		    if(user_ip.startsWith(local_ips)) {
			out.println(cbean.getError());
		    }
		}
		return;
	    }
	   

	    */
	    /*

	    //////////////////////////////////////////////////////////////////////////////
	    // database admin
	    //////////////////////////////////////////////////////////////////////////////
	    if(user_ip==null || !user_ip.startsWith(local_ips) || user_name==null || user_level <9) {
		out.println(MyMessage.htmlMessage("Sorry! ["+ sub_dir+"] has been locked for maintenance by administrator."));
		return;
	    }

	    if(action.equals("9-1")) { // admin database edit
		int row_counter = ejbdb.getRowCounter(table_name);

		query = "SELECT LIMIT "+(Integer.parseInt(pid)-1)*Integer.parseInt(max_rows)+" "+
		    max_rows+" * FROM "+table_name +" ORDER BY FIELD2 DESC, FIELD3, FIELD1 DESC;";

		ArrayList alist = new ArrayList();

		alist = ejbdb.select(query);

		StringBuffer sbf = new StringBuffer();
		sbf.append("\n<input type=hidden name=sid value="+sid+">\n");

		out.println("<HTML><HEAD>");
		out.println("<TITLE>"+table_name+"</TITLE>");
		out.println("</HEAD>"+page_color);
		out.println("<TABLE cellSpacing=0 cellPadding=1 border=0>");
		out.println("<TR>");
		out.println("<TD>");
		out.println("<B>[<A href=/servlet/MainBarServlet?sid="+sid+"&aid=1-1&tr="+row_counter+">Add</A>]</B></TD><TD>");
		
		out.println(MyHtml.pageCounter(row_counter, max_rows, pid, "MainBarServlet?sid="+sid+"&aid=9-1"));
		
		out.println("</TD>");
		out.println("</TR>");

		out.println("</TABLE>");

		out.println("<TABLE cellSpacing=0 cellPadding=2 width=100% border=1>");
		out.println("<TR>");
		out.println("<TD>&nbsp;</TD>");
		out.println("<TD>&nbsp;</TD>");
		out.println("<TD>&nbsp;</TD>");

		out.println("<TD></TD><TD>F5</TD>");
		out.println("<TD></TD><TD>F7</TD>");
		out.println("<TD></TD><TD>F11</TD>");
		out.println("<TD></TD><TD>F18</TD>");
		out.println("<TD></TD><TD>F19</TD>");
		out.println("<TD></TD><TD>F20</TD>");

		out.println("<TD>&nbsp;</TD>");
		out.println("<TD>&nbsp;</TD>");
		out.println("<TD>&nbsp;</TD>");
		out.println("</TR>");

		Iterator it = alist.iterator();
		Iterator sit = null;//alist.iterator();
		String temp = null;
		ArrayList a = null;
		int m = 0;
		int r = 0;
		while (it.hasNext()) {
		    a = (ArrayList)it.next();
		    sit = a.iterator();
		    m=1;
		    out.println("<form method=post name=postform  action=MainBarServlet>");
		    out.println("<TR>");
		   
		    out.println("<TD>");
		    out.println("<input type=submit name=aid value=Update style='font-size: 8pt'>");
		    out.println("</TD>");
		    out.println("<TD>");
		    out.println("<input type=submit name=aid value=Edit style='font-size: 8pt'>");
		    out.println("</TD>");
		    out.println("<TD>");
		    out.println("<input type=submit name=aid value=Delete style='font-size: 8pt'>");
		    out.println("</TD>");
		    while (sit.hasNext()) {
			temp = (String)sit.next();
			if(temp==null) {
			    temp ="";
			}
			if(temp.indexOf("\"") != -1) {
			    temp =  temp.replaceAll("\"","&quot;");
			}
			if(m==5 || m==7 || m==11 || m==18 || m==19 || m==20) {
			    out.println("<TD>"+r+"</TD><TD><input type=text size=20 name=f"+m+" value=\""+temp+"\"></TD>");
			}
			else {
			    out.println("<input type=hidden name=f"+m+" value=\""+temp+"\">");
			}
			m++;
		    }
		  
		    out.println("<TD>");
		    out.println("<input type=submit name=aid value=Update style='font-size: 8pt'>");
		    out.println("</TD>");
		    out.println("<TD>");
		    out.println("<input type=submit name=aid value=Edit style='font-size: 8pt'>");
		    out.println("</TD>");
		    out.println("<TD>");
		    out.println("<input type=submit name=aid value=Delete style='font-size: 8pt'>");
		    out.println("</TD>");
		    out.println("</TR>");
		    out.println("<input type=hidden name=sid value="+sid+">");
		    out.println("<input type=hidden name=call_back_aid value=9-1>");
		    out.println("<input type=hidden name=pid value="+pid+">");
		    out.println("</form>");
		    r++;
		}

		out.println("</TABLE>");
		out.println("</CENTER>");
		out.println("</BODY></HTML>");
		return;
	    }

	    if(action.equals("Delete")) {
		String call_back_aid = request.getParameter("call_back_aid");
		f1 = request.getParameter("f1");

		query = "DELETE FROM "+table_name+" WHERE FIELD1="+f1+";";
		ejbdb.delete(query);

		RequestDispatcher rd = request.getRequestDispatcher("MainBarServlet?sid="+sid+"&aid="+call_back_aid); 
		rd.forward(request,response);
		return;
	    }

	    if(action.equals("Edit")) {
		f1 = request.getParameter("f1");
		RequestDispatcher rd = request.getRequestDispatcher("MainBarServlet?sid="+sid+"&aid=2-0&f1="+f1); 
		rd.forward(request,response);
		return;
	    }

	    if(action.equals("Update")) {
		ContentDisplayBean cbean = new ContentDisplayBean();
		if(cbean.saveUpdate(request)) {
		    RequestDispatcher rd = request.getRequestDispatcher("MainBarServlet?sid="+sid+"&aid=9-1&pid="+pid); 
		    rd.forward(request,response);
		}
		else {
		    if(user_ip.startsWith(local_ips)) {
			out.println(cbean.getError());
		    }
		}
		return;
	    }

	    if(action.equals("9-0")) {
		if(user_ip.startsWith(local_ips) && user_level>=99){
		    String add_dir = request.getParameter("add_dir");
		    if(add_dir==null) {
			out.println((new ContentDisplayBean()).adminAddNewForumForm(sub_dir, table_name, sid));
			return;
		    }
		    else if(add_dir.equals("yes")) {
			ContentDisplayBean cbean = new ContentDisplayBean();
			if(!cbean.adminAddNewForum(f, sub_dir, table_name)) {
			    out.println(cbean.getError());
			    return;
			}
			else {
			    out.println("Table ["+table_name+"] and directory ["+sub_dir+"] have been added!");
			    return;
			}
		    }
		    else {
			out.println("Canceled!");
			return;
		    }
		}
		else {
		    out.println(MyMessage.htmlMessage("Sorry! ["+ sub_dir+"] has been locked for maintenance by administrator."));
		    return;		
		}
	    }
	    */
	}
	catch(IOException e) {
	    System.out.println("ContentDisplayServlet:Error:IOException:"+e);
	    return;
	}
	catch(Exception e) {
	    System.out.println("ContentDisplayServlet:Error:Exception:"+e);
	    return;
	}
    }
}






